{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ImageDataset\n",
    "\n",
    "This notebook introduces basic usages of `monai.data.ImageDataset`.\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Project-MONAI/tutorials/blob/master/modules/image_dataset.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup environment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:00.722456Z",
     "iopub.status.busy": "2021-01-14T12:34:00.721912Z",
     "iopub.status.idle": "2021-01-14T12:34:04.902827Z",
     "shell.execute_reply": "2021-01-14T12:34:04.902170Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "!python -c \"import monai\" || pip install -q \"monai-weekly[itk, pillow]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:04.909819Z",
     "iopub.status.busy": "2021-01-14T12:34:04.909227Z",
     "iopub.status.idle": "2021-01-14T12:34:07.526324Z",
     "shell.execute_reply": "2021-01-14T12:34:07.524953Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MONAI version: 0.6.0rc1+23.gc6793fd0\n",
      "Numpy version: 1.20.3\n",
      "Pytorch version: 1.9.0a0+c3d40fd\n",
      "MONAI flags: HAS_EXT = True, USE_COMPILED = False\n",
      "MONAI rev id: c6793fd0f316a448778d0047664aaf8c1895fe1c\n",
      "\n",
      "Optional dependencies:\n",
      "Pytorch Ignite version: 0.4.5\n",
      "Nibabel version: 3.2.1\n",
      "scikit-image version: 0.15.0\n",
      "Pillow version: 8.2.0\n",
      "Tensorboard version: 2.5.0\n",
      "gdown version: 3.13.0\n",
      "TorchVision version: 0.10.0a0\n",
      "ITK version: 5.1.2\n",
      "tqdm version: 4.53.0\n",
      "lmdb version: 1.2.1\n",
      "psutil version: 5.8.0\n",
      "pandas version: 1.1.4\n",
      "einops version: 0.3.0\n",
      "\n",
      "For details about installing the optional dependencies, please visit:\n",
      "    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Copyright 2020 - 2021 MONAI Consortium\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "\n",
    "# Copyright 2020 MONAI Consortium\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License.\n",
    "import os\n",
    "import tempfile\n",
    "import shutil\n",
    "\n",
    "import nibabel as nib\n",
    "import numpy as np\n",
    "\n",
    "from monai.data import ImageDataset\n",
    "from monai.transforms import Compose, EnsureChannelFirst, RandAdjustContrast, Spacing\n",
    "from monai.config import print_config\n",
    "\n",
    "print_config()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate some image data\n",
    "tempdir = tempfile.mkdtemp()\n",
    "img_ = nib.Nifti1Image(np.random.randint(0, 2, size=(20, 20, 20)), np.eye(4))\n",
    "seg_ = nib.Nifti1Image(np.random.randint(0, 2, size=(20, 20, 20)), np.eye(4))\n",
    "img_name = os.path.join(tempdir, \"img.nii.gz\")\n",
    "seg_name = os.path.join(tempdir, \"seg.nii.gz\")\n",
    "nib.save(img_, img_name)\n",
    "nib.save(seg_, seg_name)\n",
    "img_list = [img_name]\n",
    "seg_list = [seg_name]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Build a customised chain of transforms\n",
    "`TestCompose` is used to handle the additional metadata as a part of the preprocessing pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2021-01-14T12:34:07.530773Z",
     "iopub.status.busy": "2021-01-14T12:34:07.530335Z",
     "iopub.status.idle": "2021-01-14T12:34:08.080092Z",
     "shell.execute_reply": "2021-01-14T12:34:08.080424Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "image shape: (1, 14, 14, 7)\n",
      "seg. shape: (1, 14, 14, 7)\n"
     ]
    }
   ],
   "source": [
    "class TestCompose(Compose):\n",
    "    def __call__(self, data, meta):\n",
    "        data = self.transforms[0](data, meta)  # ensure channel first\n",
    "        data, _, meta[\"affine\"] = self.transforms[1](data, meta[\"affine\"])  # spacing\n",
    "        if len(self.transforms) == 3:\n",
    "            return self.transforms[2](data), meta  # image contrast\n",
    "        return data, meta\n",
    "\n",
    "\n",
    "img_xform = TestCompose([EnsureChannelFirst(), Spacing(pixdim=(1.5, 1.5, 3.0)), RandAdjustContrast()])\n",
    "seg_xform = TestCompose([EnsureChannelFirst(), Spacing(pixdim=(1.5, 1.5, 3.0), mode=\"nearest\")])\n",
    "img_dataset = ImageDataset(\n",
    "    image_files=img_list,\n",
    "    seg_files=seg_list,\n",
    "    transform=img_xform,\n",
    "    seg_transform=seg_xform,\n",
    "    image_only=False,\n",
    "    transform_with_metadata=True,\n",
    ")\n",
    "print(\"image shape:\", img_dataset[0][0].shape)\n",
    "print(\"seg. shape:\", img_dataset[0][1].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Clean up the directory"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "shutil.rmtree(tempdir)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
